package com.cjq.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cjq.domain.Admin;
import com.cjq.domain.User;
import com.cjq.mapper.AdminMapper;
import com.cjq.mapper.UserMapper;
import com.cjq.utils.Constant;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * @author junqiancai@foxmail.com
 * @since 2021/6/10 15:40
 */
@Service
public class SecurityUserDetailService implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private HttpServletRequest request;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //提供信息用于认证，认证通过后在认证通过处理器中查询权限或角色
        String type = request.getParameter(Constant.LOGIN_TYPE);
        if(Constant.ADMIN_LOGIN.equals(type)){   //管理员
            LambdaQueryWrapper<Admin> wrapper = new LambdaQueryWrapper<Admin>()
                    .eq(Admin::getUsername, username);
            Admin admin = adminMapper.selectOne(wrapper);
            if(admin==null)throw new UsernameNotFoundException("不存在该用户名");
            return admin;
        }
        //普通用户
        LambdaQueryWrapper<User> wr = new LambdaQueryWrapper<User>()
                .eq(User::getUsername, username);
        User user = userMapper.selectOne(wr);
        if(user==null)throw new UsernameNotFoundException("不存在该用户名");
        return user;
    }
}
